<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <el-button
            v-if="$permission('productClassification:add')"
            :plain="true"
            :disabled="state.addBtn"
            @click="addClass"
            >{{ $t('btn_add') }}</el-button
          >
          <el-button
            v-if="$permission('productClassification:delete')"
            :plain="true"
            :disabled="state.addBtn || state.categoryId === -1"
            @click="deleteClass"
            >删除</el-button
          >
        </div>
        <div class="left-container-header border-style-bottom">
          <el-button :plain="true" @click="downloadTemplate('category_import')"
            >下载分类模板</el-button
          >
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="importProduct"
            :before-upload="beforeProductUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入分类</el-button>
          </el-upload>

        </div>
        <div class="left-container-header border-style-bottom">
          <el-button
            :plain="true"
            @click="downloadTemplate('category_product_import')"
            >下载分类产品模板</el-button
          >
          <el-upload
            :headers="uploadProductInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="importProduct"
            :before-upload="beforeProductUpload"
            :action="uploadProductInfo.action"
          >
            <el-button>导入产品</el-button>
          </el-upload>
        </div>
        <div class="left-container-header border-style-bottom" v-if="$permission('productClassification:shifanghispull')">
          <el-button :plain="true" v-if="$permission('productClassification:shifanghispull')" @click="pullHisProductCategoryButton()">拉取HIS产品分类</el-button>
        </div>
        <div class="left-container-main main-flex">
          <el-tree
            ref="menuTree"
            :data="treeInfo.data"
            highlight-current
            :props="treeInfo.defaultProps"
            node-key="id"
            :default-expanded-keys="treeInfo.treeData"
            :default-checked-keys="[treeInfo.checked]"
            :default-expand-all="false"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </div>
      <div class="right-container" v-show="!state.saveBtn">
        <div class="layui-card-body">
          <div class="layui-btn-container border-style-bottom">
            <el-button
              v-if="$permission('productClassification:update')"
              :plain="true"
              :disabled="state.saveBtn"
              @click="update"
              >{{ $t('btn_save') }}</el-button
            >
          </div>
          <div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formOrgInfo.ref"
              :data="formOrgInfo.data"
              :field-list="formOrgInfo.fieldList"
              :rules="formOrgInfo.rules"
              :label-width="formOrgInfo.labelWidth"
            >
              <!--<template v-slot:form-depotName>-->
              <!--<el-input type="input" :disabled="true" placeholder="请选择仓库"-->
              <!--v-model="formOrgInfo.data.depotName">-->
              <!--<i @click="openDepotWindow" slot="append" v-if="!saveBtn"-->
              <!--class="el-icon-more i_more"></i>-->
              <!--</el-input>-->
              <!--</template>-->
            </page-form>
          </div>
        </div>
        <div v-if="state.isAddUpdate === 'update'" class="layui-card-body">
          <div class="opt-header border-style-bottom">
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-button>
                <el-button
                  v-if="$permission('productClassification:updateConnection')"
                  :disabled="btnDelete"
                  style="margin-right: 12px"
                  @click="deleteProduct()"
                  >删除</el-button
                >
              </template>
            </page-filter>
          </div>
          <div>
            <page-table
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :api="tableInfo.api"
              :query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :isDynamic="true"
              @handleEvent="handleEvent"
            >
              <template v-slot:col-licenseNumber="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
              <template v-slot:col-commonName="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
              <template v-slot:col-type="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.productCategoryValue || '-' }}</p>
              </template>
              <template v-slot:col-standard="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
            </page-table>
          </div>
        </div>
      </div>
    </div>
    <select-product
      v-if="state.showProduct"
      :api="getProductCategoryExcludePage"
      v-model:show-dialog="state.showProduct"
      :query="state.params"
      @callback="changeProduct"
    ></select-product>
  </div>
</template>

<script setup name="productClassification">
import PageTable from '@/components/PageTable/index'
import PageForm from '@/components/PageForm/index'
import PageFilter from '@/components/PageFilter/index'
import {
  batchInsertMappingCategoryProduct,
  batchDeleteMappingCategoryProduct,
} from '@/api/mapping.js'
import {
  getProductCategoryTree,
  addProductCategory,
  updateProductCategory,
  getProductCategoryDetails,
  getProductCategoryPage,
  deleteProductCategoryOne,
  getProductCategoryExcludePage,
  pullHisProductCategory,
} from '@/api/core'
import selectProduct from '@/components/SelectProduct/index'
import { ElLoading, ElMessage } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'

const { proxy } = getCurrentInstance()

const state = reactive({
  addBtn: true, //控制左侧树节点上方新增按钮状态
  saveBtn: true,
  addOrUpdate: '',
  RightBox: false,
  selectRows: [],
  tableData: [], //编辑的用户数据
  showProduct: false,
  categoryId: '',
  isAddUpdate: 'add',
  params: {},
})

const uploadInfo = reactive({
  action: axios.defaults.baseURL + '/core/productCategory/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const uploadProductInfo = reactive({
  action: axios.defaults.baseURL + '/mapping/categoryProduct/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 权限树
const treeInfo = reactive({
  data: [],
  nodeKey: 'code',
  treeData: [],
  checked: [],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
})
const formOrgInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '分类名称',
      value: 'name',
      type: 'input',
      maxlength: 20,
      required: true,
    },
    {
      label: '品名举例',
      value: 'categoryExample',
      type: 'textarea',
      required: true,
    },
    {
      label: '财务科目',
      value: 'financialAccount',
      show: true,
      type: 'select-model',
      clearable: true,
      checkDefault: false,
      code: 'financial_account',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    searchType: 'product',
    categoryId: '',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      event: addProduct,
      show: proxy.$permission('productClassification:updateConnection'),
    },
    { type: 'slot', value: 'button' },
    {
      type: 'input',
      label: '名称/通用名/英文/备注',
      clearable: true,
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  selections: [],
  data: [],
  api: getProductCategoryPage,
  fieldList: [
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    //TODO：需求有问题
    // { label: "英文名称", value: "enName"},
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '状态', value: 'statusValue', width: '100px' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: deleteProduct,
        show: proxy.$permission('productClassification:updateConnection'),
      },
    ],
  },
})

const btnDelete = computed(() => {
  return !tableInfo.selections.length
})
watch(
  () => treeInfo.data,
  () => {
    state.RightBox = false
    state.addBtn = true
    state.saveBtn = true
  },
  {
    deep: true,
  }
)
initRules()

onMounted(() => {
  init()
})

function init() {
  getProductCategoryTree().then((res) => {
    if (res && res.success) {
      let data = [res.data]
      treeInfo.data = data
      getNodeId(data, 2)
    }
  })
}
function getNodeId(data, num, count = 0) {
  count++
  data.forEach((item) => {
    if (count === num) {
      return
    }
    treeInfo.treeData.push(item.id)
    if (item.children && item.children.length) {
      getNodeId(item.children, num, count)
    }
  })
}
// 初始化校验规则
function initRules() {
  // const formOrgInfo = formOrgInfo;
  formOrgInfo.rules = proxy.$initRules(formOrgInfo.fieldList)
}
function addClass() {
  state.addOrUpdate = addProductCategory
  state.isAddUpdate = 'add'
  state.RightBox = false
  formOrgInfo.data = {}
  tableInfo.data = []
  tableInfo.selections = []
  let parent = proxy.$refs.menuTree.getCurrentNode()
  state.saveBtn = false
  formOrgInfo.data = {
    pid: parent.id,
  }
}
// 删除分类
function deleteClass() {
  proxy
    .$confirm(
      '删除该分类将会清空所有的子分类，如果存在关联产品则无法删除，确认删除吗？?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      let id = state.categoryId //当前节点id
      deleteProductCategoryOne(id).then((res) => {
        if (res.success) {
          init()
          state.isAddUpdate = 'add'
          formOrgInfo.data.name = ''
          formOrgInfo.data.remark = ''
        }
      })
    })
    .catch(() => {})
}
function getDetail() {
  getProductCategoryDetails(state.categoryId).then((res) => {
    formOrgInfo.data = {
      ...res.data,
    }
  })
}
function loadList() {
  filterInfo.query.productCategory = state.categoryId
  proxy.$nextTick(function () {
    tableInfo.refresh = Math.random()
  })
}
// 点击树节点
function handleNodeClick(node) {
  formOrgInfo.ref.resetFields()
  state.addBtn = false
  state.addOrUpdate = updateProductCategory
  state.categoryId = node.id
  if (node.id !== -1) {
    state.isAddUpdate = 'update'
    state.saveBtn = false
    state.categoryId = node.id
    getDetail()
    state.RightBox = true
    loadList()
  } else {
    state.isAddUpdate = 'add'
    formOrgInfo.data = {}
    state.saveBtn = true
    state.RightBox = false
  }
}
function search() {
  // const tableInfo = tableInfo;
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function listSelect(rows) {
  state.selectRows = []
  for (let item of rows) {
    state.selectRows.push(item.id)
  }
}
function update() {
  // const formOrgInfo = formOrgInfo;
  formOrgInfo.ref.validate((valid) => {
    if (valid) {
      state.addOrUpdate(formOrgInfo.data).then((res) => {
        if (res.success) {
          init()
        }
      })
    }
  })
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function deleteProduct(row) {
  let arr = []
  if (row) {
    arr = [row.id]
  } else {
    tableInfo.selections.forEach((item) => {
      arr.push(item.id)
    })
  }
  if (arr.length) {
    batchDeleteMappingCategoryProduct(arr).then((res) => {
      if (res) {
        loadList()
      }
    })
  }
}
function changeProduct(data) {
  state.showProduct = false
  if (data && data.length) {
    let arr = data.map((item) => {
      return {
        categoryId: state.categoryId,
        productId: item.productId,
        id: item.id,
      }
    })
    batchInsertMappingCategoryProduct(arr).then((res) => {
      if (res) {
        loadList()
      }
    })
  }
}
function addProduct() {
  state.showProduct = true
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    init()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
function downloadTemplate(tag) {
  exportTemplateExcel(tag).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function pullHisProductCategoryButton() {
  pullHisProductCategory().then((res) => {
    if (res && res.success) {
      ElMessage.success({
        duration: 3000,
        showClose: true,
        message: res.msg,
      });
      init();
    }else{
      ElMessage.error({
        message: res.msg,
        duration: 0,
        showClose: true,
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 62px);
}
.left-container {
  min-width: 320px;
  .left-container-header {
    display: flex;
    justify-content: space-around;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 290px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
  }
}
</style>
